<template>
  <el-select
      v-model="querySelectUser"
      multiple
      filterable
      remote
      reserve-keyword
      :placeholder="'搜索'+title+'...'"
      remote-show-suffix
      :collapse-tags="false"
      :remote-method="queryUser"
      :loading="loading"
      :multiple-limit="max"
      @change="queryChange"
      style="width:100%"
  >
    <el-option
        v-for="item in queryOptions"
        :key="item.id"
        :label="item.name"
        :value="item.id"
    />
  </el-select>
</template>

<script>
import {searchSelectVariableQuery} from "@/api/BusinessForDesignApi";

export default {
  name: "SelectUserDialog",
  props:{
    tenant:{
      type:String,
      default:''
    },
    ok:{
      type:Function,
      default:null
    },
    title:{
      type:String,
      default:'选择信息'
    },
    variableType:{
      type:String,
      default:'client.directUser'
    },
    max:{
      type:Number,
      default:0
    },
    initData:{
      type:Array,
      default:null
    }
  },
  data() {
    return {
      loading:false,
      queryOptions:[],
      querySelectUser: [],
      tempSelect:{}//临时选择的节点
    }
  },
  mounted() {
    if(this.initData){
      for (let i = 0; i < this.initData.length; i++) {
        let temp = this.initData[i]
        if(temp&&temp.id){
          this.querySelectUser.push(temp.id)
          this.queryOptions.push(temp)
        }
      }
    }
  },
  methods: {
    // 搜索的用户数据。添加到右侧
    queryChange(h){
      // 把选中过的值缓存起来
      for (let i = 0; i <h.length; i++) {
        let id = h[i]
        if(!this.tempSelect[id]){
          for (let j = 0; j < this.queryOptions.length; j++) {
            let temp = this.queryOptions[j]
            if(temp.id==id){
              this.tempSelect[id]=temp
            }
          }
        }
      }
      if(this.ok){
        let temp = []
        for (let i = 0; i <h.length; i++) {
          temp.push(this.tempSelect[h[i]])
        }
        this.ok(temp)
      }
    },
    queryUser(keyword){
      let data = {
        'variableType':this.variableType,
        'type':'query',
        'query':keyword,
        '_tenant':this.tenant
      }
      searchSelectVariableQuery(data).then(res=>{
        this.queryOptions=res.data.result
      }).catch(res=>{
        console.log(res)
        this.$notify.error({title: '提示',message: '调用查询接口失败',showClose: false })})
    }
  }
}
</script>

<style>
</style>
